package com.wyu.blog.controller;


import com.wyu.blog.entity.Article;
import com.wyu.blog.entity.Collect;
import com.wyu.blog.entity.LoginTicket;
import com.wyu.blog.entity.User;
import com.wyu.blog.service.ArticleService;
import com.wyu.blog.service.CollectService;
import com.wyu.blog.service.LoginTicketService;
import com.wyu.blog.service.UserService;
import com.wyu.blog.util.BlogUtil;
import com.wyu.blog.util.RecommendUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * Created by hgq on 2020/2/1.
 */
@Controller
public class LoginController {

    @Autowired
    private UserService userService;

    @Autowired
    private ArticleService articleService;

    @Autowired
    private LoginTicketService loginTicketService;

    @Autowired
    private CollectService collectService;

    /**
     * 找到推荐文章的标题
     */
    @SuppressWarnings({ "rawtypes", "unchecked" })
    public List<Article> recommend2(User user){

        ArrayList collList = new ArrayList();
        ArrayList notCollList = new ArrayList();
        List<Collect> collArticle = collectService.findCollectByUserId(user.getUserId());
        List<Collect> notCollArticle = collectService.findNotCollect(user.getUserId());
        ArrayList list = new ArrayList();

        for(Collect collect : collArticle){
            collList.add(collect.getArticle().getArticleTitle());
        }
        for(Collect notCollect : notCollArticle) {
            notCollList.add(notCollect.getArticle().getArticleTitle());
        }
        for(int i = 0; i < collList.size(); i++){
            for(int j = 0; j < notCollList.size(); j++) {
                float n = RecommendUtil.levenshtein(collList.get(i).toString(), notCollList.get(j).toString());
                Map tempMap = new HashMap();
                tempMap.put("number",n);
                tempMap.put("name",notCollList.get(j));
                list.add(tempMap);
            }
        }

        Collections.sort(list, new Comparator<Map<String, Object>>(){

            public int compare(Map<String, Object> o1, Map<String, Object> o2) {
                Float num1 =(Float)o1.get("number");//name1是从你list里面拿出来的一个
                Float num2= (Float)o2.get("number"); //name1是从你list里面拿出来的第二个name
                return -num1.compareTo(num2);
            }

        });

        List newList = list.subList(0, 5);
        List nameList = new ArrayList();
        List<Article> recommendArticle = new ArrayList<>();
        for (int i = 0; i < newList.size(); i++) {
            Map<String, Object> maps = (Map<String, Object>) newList.get(i);
            String name = maps.get("name").toString();
            int a = 1;
            nameList.add(name);
            Article article = articleService.findArticleByTitle(name);
            recommendArticle.add(article);
        }


        return recommendArticle;
    }

    private String addLoginTicket(Integer userId){
        LoginTicket loginTicket = new LoginTicket();
        loginTicket.setUserId(userId);
        Date date = new Date();
        date.setTime(date.getTime()+1000*3600*12);
        loginTicket.setUserExpired(date);
        loginTicket.setUserStatus(0);
        loginTicket.setUserTicket(UUID.randomUUID().toString().replaceAll("-",""));
        loginTicketService.addLoginTicket(loginTicket);

        return loginTicket.getUserTicket();
    }

    public Map<String,String> loginCheck(String username, String password) {
        Map<String, String> map = new HashMap<>();
        User user = userService.findUserByName(username);
        //免密码登录
        if(!user.getUserPassword().equals(BlogUtil.MD5(password + user.getUserSalt()))){
            map.put("msg", "密码错误");
            return map;
        }
        String ticket = addLoginTicket(user.getUserId());
        map.put("ticket", ticket);
        return map;
    }

    /**
     * 后台管理员登录
     */
    @RequestMapping(value = "/admin/login")
    public String adminLogin(@RequestParam("username") String username,
                        @RequestParam("password") String password,
                        Map<String,String> map, HttpSession session){
        User user = userService.findUserByName(username);
        if(user == null) {
            map.put("msg", "该用户不存在");
            return "admin/login";
        }else if (user.getUserPassword().equals(BlogUtil.MD5(password + user.getUserSalt()))
                && user.getRole().getRoleName().equals("管理员")) {
             session.setAttribute("admin", user);
             return "admin/user";
        }else if(!user.getRole().getRoleName().equals("管理员")) {
            map.put("msg", "没有权限登录");
            return "admin/login";
        }else {
             map.put("msg", "密码错误");
             return "admin/login";
        }
    }


    /**
     * 用户登录
     */
    @RequestMapping(value = "/blog")
    public String login(@RequestParam("username") String username,
                        @RequestParam("password") String password,
                        Map<String,String> map, HttpSession session, Model model, HttpServletResponse response){
        User user = userService.findUserByName(username);
        if(user == null) {
            map.put("msg", "该用户不存在");
            return "login";
        }else{

//            Map<String,String> maps = loginCheck(username,password);
//            if (maps.containsKey("ticket")) {
//                Cookie cookie = new Cookie("ticket",maps.get("ticket"));
//                cookie.setPath("/");
//                response.addCookie(cookie);
//                System.out.println(cookie);
//                System.out.println("免密码登录了");
//
//                session.setAttribute("loginUser", user);
//                List<Article> topArticle = articleService.findTopArticle();
//                model.addAttribute("topArticle", topArticle);
//                return "main";
//            }else {

                if (user.getUserPassword().equals(BlogUtil.MD5(password + user.getUserSalt()))
                        && user.getRole().getRoleName().equals("普通用户")) {
                    session.setAttribute("loginUser", user);
                    List<Article> topArticle = articleService.findTopArticle();
                    List<Article> hotArticle = articleService.findHotArticle();
                    List<Collect> collArticle = collectService.findCollectByUserId(user.getUserId());
                    if (!collArticle.isEmpty()) {
                        List<Article> recommendArticle = recommend2(user);
                        model.addAttribute("recommendArticle", recommendArticle);
                    } else {
                        model.addAttribute("recommendArticle", null);
                    }
                    List<Article> recentArticle = articleService.findRecentArticle();
                    model.addAttribute("topArticle", topArticle);
                    model.addAttribute("hotArticle", hotArticle);
                    model.addAttribute("recentArticle", recentArticle);
//                    System.out.println("使用密码登录");
                    return "main";
                } else if (!user.getRole().getRoleName().equals("普通用户")) {
                    map.put("msg", "没有权限登录");
                    return "login";
                } else {
                    map.put("msg", "密码错误");
                    return "login";
                }
            }
//        }
    }

    /**
     * 用户注册
     */
    @RequestMapping("/user/register")
    public String register(@RequestParam("username") String username, @RequestParam("password") String password,
                           Map<String,Object> map) throws NullPointerException{
        User user = userService.findUserByName(username);
        if(user != null){
            map.put("msg","用户已存在");
            return "register";
        }else if(username.contains(" ")) {
            map.put("msg", "用户名不能存在空格");
            return "register";
        }else if(username.length() > 10){
            map.put("msg", "用户名长度不能超过10个字符");
            return "register";
        }else{
            User newUser = new User();
            newUser.setUserName(username);
            newUser.setUserSalt(UUID.randomUUID().toString().substring(0, 5));
            newUser.setUserPassword(BlogUtil.MD5(password + newUser.getUserSalt()));
            newUser.setUserRegistrationTime(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()));
            userService.addUser(newUser);
            map.put("msg1","注册成功");
            return "register";
        }
    }

    /**
     * 用户退出登录
     */
    @GetMapping(value = "sign_out")
//    ,@CookieValue("ticket") String ticket
    public String signOut1(HttpServletRequest request){
        //false代表：不创建session对象，只是从request中获取。
        HttpSession session = request.getSession(false);
        if(session != null) {
            session.removeAttribute("loginUser");
        }
        return "login";
    }

    /**
     * 管理员退出登录
     */
    @GetMapping(value = "/admin/sign_out")
    public String signOut2(HttpServletRequest request){
        //false代表：不创建session对象，只是从request中获取。
        HttpSession session = request.getSession(false);
        if(session != null) {
            session.removeAttribute("admin");
        }

        return "admin/login";
    }

    /**
     * 登录与注册切换
     */
    @GetMapping(value = "/sign_in")
    public String signIn(){
        return "login";
    }

    @GetMapping(value = "/sign_up")
    public String signUp(){
        return "register";
    }

}

